//
//  YAYIOrderdetailController.m
//  YAYIDoctor
//
//  Created by hxp on 16/5/6.
//  Copyright © 2016年 hxp. All rights reserved.
//

#import "YAYIOrderdetailController.h"
#import "YAYIOrderDetailCell.h"
#import "YAYIOrderServiceModel.h"
#import "YAYIGroupModel.h"
#import "YAYIAvatarCell.h"
#import "YAYIPatienInfoController.h"
//#import "YAYIOrderRefundsController.h"

#import "YAYIRefundDetailController.h"

#import "YAYIRefundOrderCell.h"
#import "YAYIRefoundOrderModel.h"


@interface YAYIOrderdetailController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)UIView *headerView;
@property (nonatomic,strong)NSMutableArray *dataAry;
@property (nonatomic,strong)UILabel *statue;
@property (nonatomic,strong)NSMutableArray *serviceAry;
/** 退款订单 */
@property (nonatomic, strong)  NSMutableArray *refundOrderArray;


@end

@implementation YAYIOrderdetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.serviceAry = [NSMutableArray array];
    self.dataAry = [NSMutableArray array];
    self.refundOrderArray = [NSMutableArray array];
    
    [self createHeaderView];
    [self createTableView];
    
    [self getUserInfo];
    [self orderDetail];
    
}


-(void)createHeaderView{
    if (self.headerView == nil) {
        self.headerView = [UIView new];
        self.headerView.backgroundColor = [UIColor colorWithWhite:0.965 alpha:1];
        [self.view addSubview:self.headerView];
    }
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@(0));
        make.right.mas_equalTo(@(0));
        make.size.mas_equalTo(CGSizeMake(SCREEN_width, 30));
    }];
    if (self.statue == nil) {
        self.statue = [UILabel new];
        self.statue.textAlignment = NSTextAlignmentCenter;
        self.statue.attributedText =[self content:@"订单状态" name:[NSString payState:[NSString stringWithFormat:@"%@",self.state]]];
        self.statue.font = [UIFont systemFontOfSize:font13];
        [self.headerView addSubview:self.statue];
    }
    [self.statue mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.headerView.center);
        make.size.mas_equalTo(CGSizeMake(180, 20));
       
    }];
}


-(NSMutableAttributedString *)content:(NSString *)title name:(NSString *)name
{
    NSString *string = [NSString stringWithFormat:@"%@：%@",title,name];
    NSMutableAttributedString *maString = [[NSMutableAttributedString alloc] initWithString:string];
    NSRange rang =  [string  rangeOfString:@"："];
    [maString  addAttribute:NSForegroundColorAttributeName  value:[UIColor lightGrayColor] range:NSMakeRange(0, rang.location + 1)];
    [maString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(rang.location + 1, maString.length - rang.location -1)];
    return maString;
}

-(void)createTableView
{
    if (self.tableView == nil) {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_width, SCREEN_height - 64) style:UITableViewStyleGrouped];
        self.tableView.dataSource = self;
        self.tableView.delegate = self;
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.tableView.showsVerticalScrollIndicator = NO;
        [self.view addSubview:self.tableView];
    }
}


-(UIView *)sectionHeaderViewWithTitle:(NSString *)titleStr
{
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_width, 40)];
    headerView.backgroundColor = [UIColor colorWithWhite:0.965 alpha:1];
    UIView *sectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_width, 40)];
    sectionView.backgroundColor = [UIColor whiteColor];
    [headerView addSubview:sectionView];
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 100, 20)];
    title.text = titleStr;//@"项目明细";
    title.textColor = [UIColor blackColor];
    [sectionView addSubview:title];
    UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(0, 39.5, SCREEN_width, 0.5)];
    line.backgroundColor = YAYIColor(0xdd, 0xdd, 0xdd);
    [headerView  addSubview:line];
    
    return headerView;

}


#pragma mark - 获取数据
-(void)getUserInfo{
    
    YAYILog(@"userid:%@", self.userid);
    
    [YAYINetWorking getWithURL:patientDetail_url param:@{@"userid":self.userid} finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        
        if (nil == error) {
            
            if ([dict[@"status"] isEqualToString:@"success"]) {
                
                NSString *avatar = dict[@"data"][@"avatar"];
                self.avatar = avatar;
                
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
                YAYIAvatarCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
                
                [cell.avatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", API, avatar]] placeholderImage:[UIImage imageNamed:@"1"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                    
                }];
            }
        }else{
            
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:error.userInfo[@"com.alamofire.serialization.response.error.data"] options:NSJSONReadingMutableContainers error:nil];
            YAYILog(@"erro:%@", dict);
            [SVProgressHUD showImage:nil status:[NSString stringWithFormat:@"\n\n%@\n\n", dict[@"message"]]];
        }
        
    }];
    
}

-(void)orderDetail
{
    if (self.orderid != nil) {
        NSMutableString *svices = [NSMutableString string];
        
        NSString *urlStr = didPay_order_detail_url;
        if (self.isRefund) {
            urlStr = refunds_url;
        }
        
        [YAYINetWorking getWithURL:didPay_order_detail_url param:@{@"orderid":self.orderid} finish:^(NSData *data, NSDictionary *dict, NSError *error) {
            
            YAYILog(@"返回：%@", dict);
            
            if ([dict[@"status"] isEqualToString:@"success"]) {
                
                NSDictionary *map = dict[@"map"];
                NSArray *oderServices = map[@"oderServices"];
                for (NSDictionary *obj in oderServices) {
                    
                    YAYIOrderServiceModel *model = [YAYIOrderServiceModel new];
                    [model setValuesForKeysWithDictionary:obj];
                    model.title = model.servicename;
                    [self.serviceAry addObject:model];
                    [svices appendFormat:@"%@", model.id];
                    [svices appendString:@","];
                    [svices appendFormat:@"%@",model.amount];
                    [svices appendString:@";"];
                }
                
                // 存储退款订单，如果是退款订单进去就得显示退款列表
                if (self.isRefund) {
                    NSArray *refundOrder = map[@"refund"];
                    for (NSDictionary *dictObj in refundOrder) {
                        
                        YAYIRefoundOrderModel *refundOrderModel = [[YAYIRefoundOrderModel alloc] init];
                        [refundOrderModel setValuesForKeysWithDictionary:dictObj];
                        [self.refundOrderArray addObject:refundOrderModel];
                    }
                }
                

                [self createDataSource];
            }
        }];
        
    }
}


-(void)createDataSource
{
    [self.dataAry removeAllObjects];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableArray *group0 = [NSMutableArray array];
        NSMutableArray *group1 = [NSMutableArray array];
        NSMutableArray *group2 = [NSMutableArray array];
        NSMutableArray *group3 = [NSMutableArray array];
        YAYIGroupModel *group = [[YAYIGroupModel alloc] init];
        
        group.avatar = [NSString stringWithFormat:@"%@%@",API,_avatar];
        group.name = [NSString  stringWithFormat:@"%@ (%@)",_patientname,_clientname];
        group.phone = self.mobile;
        [group0 addObject:group];
        
        NSArray *titleAry = @[@"就诊医院"];
        NSArray *name = @[_hospital];
        for (int i = 0; i< name.count; i ++) {
            YAYIGroupModel *group = [[YAYIGroupModel alloc] init];
            group.title = titleAry[i];
            group.name = name[i];
            [group1  addObject:group];
        }
        
        NSArray *title1 = @[@"本单优惠",@"合计应收",@"优惠后金额"];
        NSArray *name1 = @[self.reduce, self.totalPrice, self.reducePrice];
        for (int i = 0; i< name1.count; i ++) {
            YAYIGroupModel *group = [[YAYIGroupModel alloc] init];
        
            group.title = title1[i];
            
            CGFloat amount = [name1[i] floatValue] / 100;
            group.name = [NSString stringWithFormat:@"￥%.2f", amount];
            [group2  addObject:group];
        }
        
        NSArray *title2 = @[@"收款方式"];
        NSArray *name2 = @[@"在线支付"];
        for (int i = 0; i< name2.count; i ++) {
            YAYIGroupModel *group = [[YAYIGroupModel alloc] init];
            group.title = title2[i];
            group.name = name2[i];
            [group3  addObject:group];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.dataAry addObject:group0];
            [self.dataAry addObject:group1];
            [self.dataAry addObject:self.serviceAry];
            [self.dataAry addObject:group2];
            [self.dataAry addObject:group3];
            [self.tableView     reloadData];
        });
    });
}



#pragma mark - 代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.isRefund && self.refundOrderArray.count > 0) {
        return self.dataAry.count + 1;
    } else {
        return self.dataAry.count;
    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 2 || section == 5) {
        return 40;
    }
    return 0.01;
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section  == 2) {    // 项目明细"
        return [self sectionHeaderViewWithTitle:@"项目明细"];
    }else if (section  == 5){   // 退款记录
        return [self sectionHeaderViewWithTitle:@"退款记录"];
    }
    return [UIView new];
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0 || section == 4) {
        return [self.dataAry[section] count];
    }else if (section == 1){
        return 1;
    }else if (section == 2){
        return self.serviceAry.count;
    }else if (section == 3){
        return [self.dataAry[section] count];
    }else if (section == 5){
        return self.refundOrderArray.count;;
    }
    return 0;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 78;
    }else if (indexPath.section == 1 || indexPath.section == 2 || indexPath.section == 4) {
        return 44;
    }else if (indexPath.section == 5){
        return 56;
    }else{
        return 35;
    }
    
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        static NSString *identifer = @"avatarCell";
        YAYIAvatarCell *cell = [tableView dequeueReusableCellWithIdentifier:identifer];
        if (cell == nil) {
            cell = [[YAYIAvatarCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifer];
        }
        
        YAYIGroupModel *model = self.dataAry[indexPath.section][indexPath.row];
        [cell.avatar sd_setImageWithURL:[NSURL URLWithString:model.avatar] placeholderImage:[UIImage imageNamed:@"1"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
        }];
        cell.phone.text = model.phone;
        cell.name.text =  model.name;
        cell.icon.hidden = NO;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }else{
        
        if (indexPath.section == 1 || indexPath.section == 3 || indexPath.section == 4) {
            
            static NSString *identifer = @"identifer1";
            YAYIOrderDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:identifer];
            if (cell == nil) {
                cell = [[YAYIOrderDetailCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifer];
            }
            cell.section = indexPath.section;
            cell.row = indexPath.row;
            
            YAYIGroupModel *model = self.dataAry[indexPath.section][indexPath.row];
            cell.title.text = model.title;
            cell.name.text = [NSString stringWithFormat:@"%@",model.name];
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell;
        }else if (indexPath.section == 2){
            
            static NSString *identifer = @"identifer2";
            YAYIOrderDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:identifer];
            if (cell == nil) {
                cell = [[YAYIOrderDetailCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifer];
            }
            cell.section = indexPath.section;
            cell.row = indexPath.row;
            
            YAYIOrderServiceModel *model = self.dataAry[indexPath.section][indexPath.row];
            cell.title.text = model.servicename;
            
            CGFloat price = [model.price floatValue] / 100;
            cell.name.text = [NSString stringWithFormat:@"￥%.2f", price];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell;
        }else if (indexPath.section == 5){
            
            YAYIRefoundOrderModel *model = self.refundOrderArray[indexPath.row];
            YAYIRefundOrderCell *cell = [YAYIRefundOrderCell cellWith:tableView];
            cell.model = model;
            
            return cell;
        }
    }
    
    return nil;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (0 == indexPath.section) {
        
        YAYIPatienInfoController *patientInfoVc = [[YAYIPatienInfoController alloc] init];
        patientInfoVc.isAccepted = YES;
        patientInfoVc.userid = [NSString stringWithFormat:@"%@", self.userid];
        YAYILog(@"patientInfoVc.userid:%@", patientInfoVc.userid);
        [self.navigationController pushViewController:patientInfoVc animated:YES];
    }else if (5 == indexPath.section){
        
        YAYIRefoundOrderModel *model = self.refundOrderArray[indexPath.row];
        
        YAYIRefundDetailController *refundVc = [[YAYIRefundDetailController alloc] init];
//        refundVc.pageType = PageTypeDetail;
    
        refundVc.title = @"退款详情";
        refundVc.noPayModel = self.noPayModel;
        
        refundVc.ordercontent = model.remark;
        refundVc.patientname = self.patientname;
//        refundVc. = self.hospital;
        refundVc.clientname = self.clientname;
        refundVc.mobile = self.mobile;
        refundVc.orderid = [NSString stringWithFormat:@"%zd", model.orderid];
        refundVc.totalPrice = self.totalPrice;
        refundVc.reduce = [NSString stringWithFormat:@"%zd", model.money];
        refundVc.userid = self.userid;
        refundVc.avatar = self.avatar;
        refundVc.refundstate = [NSString stringWithFormat:@"%zd", model.type];
        
        
        [self.navigationController pushViewController:refundVc animated:YES];
    }
}


@end
